#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

struct Edge
{
    int a, b, w;

    bool operator< (const Edge& W)const{
        return w < W.w;
    }
};

const int N = 2010, M = 10010;

int n, m, cnt, mcnt;
Edge edge[M], medge[M];
int p[N];


int find(int x){
    if(x != p[x]){
        p[x] = find(p[x]);
    }

    return p[x];
}

int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    scanf("%d%d", &n, &m);
    int res = 0;
    for(int i = 0; i < m; i ++){
        int p, u, v, z;
        scanf("%d%d%d%d", &p, &u, &v, &z);
        if(p == 1){
            medge[mcnt].a = u;
            medge[mcnt].b = v;
            medge[mcnt].w = z;
            mcnt ++;
        }else{
            edge[cnt].a = u;
            edge[cnt].b = v;
            edge[cnt].w = z;
            cnt ++;
        }
    }

    for(int i = 1; i <= n; i ++){
        p[i] = i;
    }

    for(int i = 0; i < mcnt; i ++){
        int x = medge[i].a;
        int y = medge[i].b;
        int z = medge[i].w;

        int a = find(x);
        int b = find(y);
        p[a] = p[b];
        res += z;
    }

    sort(edge, edge + cnt);

    for(int i = 0; i < cnt; i ++){
        int x = edge[i].a;
        int y = edge[i].b;
        int z = edge[i].w;

        int a = find(x);
        int b = find(y);

        if(a != b){
            p[a] = p[b];
            res += z;
        }
    }

    printf("%d", res);

    return 0;
}